﻿using System;
using System.Security.Principal;
using System.Web;
using System.Web.Security;

namespace Solution
{
    /// <summary>
    /// from 验证，生成票据
    /// </summary>
    public static class FormTicketHelper
    {
        #region 公共方法

        /// <summary>
        /// 取得票据中数据(一般为UserName)
        /// </summary>
        /// <returns></returns>
        public static string GetUserData()
        {
            var fid = HttpContext.Current.User.Identity as FormsIdentity;
            return fid == null ? "" : fid.Ticket.UserData;
        }

        /// <summary>
        /// 取得登录用户ID
        /// </summary>
        /// <returns></returns>
        public static string GetUserId()
        {
            return HttpContext.Current.User.Identity.Name;
        }

        /// <summary>
        /// 是否是AJAX请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool IsAjax(this HttpRequest request)
        {
            return request.IsAjax();
        }

        /// <summary>
        /// 通过此法判断登录
        /// </summary>
        /// <returns>已登录返回true</returns>
        public static bool IsLogin()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public static void Logout()
        {
            FormsAuthentication.SignOut();
        }

        /// <summary>
        /// 创建一个票据，放在cookie中
        /// 票据中的数据经过加密，解决了cookie的安全问题。
        /// </summary>
        /// <param name="response">HttpContext Response 扩展</param>
        /// <param name="userId">用户ID</param>
        /// <param name="userData">用户数据(用户角色)</param>
        /// <param name="rememberMe">是否记住当前用户（如果记住，则保持cookie 1个月）</param>
        /// <param name="prefix">票据前缀</param>
        public static void SetAuthCookie(this HttpResponseBase response, string userId, string userData, bool rememberMe = false, string prefix = "ucenter_admin_")
        {
            var expire = DateTime.Now.Add(FormsAuthentication.Timeout);  //默认过期时间，30分钟
            if (rememberMe)  //记住密码，记住1个月
            {
                expire = DateTime.Now.AddDays(30);
            }
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                       1,
                                                       userId,
                                                       DateTime.Now,
                                                       expire,
                                                       rememberMe,
                                                       userData,
                                                       FormsAuthentication.FormsCookiePath
                                                   );

            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.Value = FormsAuthentication.Encrypt(ticket);
            cookie.Expires = expire;
            response.Cookies.Add(cookie);

            //SetAuthCookie方法用于标识用户的Identity状态为true
            //FormsAuthentication.SetAuthCookie(userId, true);

            //guest cookie
            //var guestCookie = new HttpCookie("GUESTID", Guid.Empty.ToString());
            //guestCookie.Expires = DateTime.Now.AddYears(-1);
            //response.Cookies.Add(guestCookie);

            //重写HttpContext中的用户身份，可以封装自定义角色数据；
            //判断是否合法用户，可以检查：HttpContext.User.Identity.IsAuthenticated的属性值
            //string[] roles = ticket.UserData.Split(',');
            //IIdentity identity = new FormsIdentity(ticket);
            //IPrincipal principal = new GenericPrincipal(identity, roles);
            //HttpContext.Current.User = principal;

            //HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// EXCEL表格的响应头
        /// </summary>
        /// <param name="response"></param>
        /// <param name="filename"></param>
        public static void ToExcel(this HttpResponseBase response, string filename)
        {
            response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
            response.Charset = "UTF-8";
            response.ContentEncoding = System.Text.Encoding.Default;
            response.ContentType = "application/ms-excel";
        }

        #endregion 公共方法
    }
}